/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Modulo3;

import Modelo.DAL.InformeRiesgos_DAO;
import Modelo.DAL.InformeRiesgos2_DAO;
import Acceso.Security;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMessage;
import com.lowagie.text.pdf.PdfCopyFields;
import com.lowagie.text.pdf.PdfReader;
import java.io.*;

/**
 *
 * @author Juan Reyes
 */
public class informeRiesgosAction extends org.apache.struts.action.Action {

    /* forward name="success" path="" */
    private static final String SUCCESS = "success";
    private static final String FAILURE = "failure";
    private static final String[] ALLOWED = {"Administrador","Generar Informes de Riesgo"};

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        if (!Security.validateSession(request, ALLOWED)) {
            Security.privilegeError(response);
            return mapping.findForward("errorPriv");
        }

        informeRiesgosForm formBean = (informeRiesgosForm) form;
        String cedula = formBean.getNacionalidad() + "-" + formBean.getCedula();
        String r_puesto_trabajador = formBean.getRelacionPuestoTrabajador();
        String examenes_medicos = formBean.getExamenesMedicos();
        byte[] informePDF = null;
        byte[] informePDF2 = null;
        ActionErrors errors = new ActionErrors();
        boolean error = false;

        if (cedula == null || cedula.equals("-") || cedula.equals("V-") || cedula.equals("E-")) {
            errors.add("ci_ir_requerido", new ActionMessage("errors.ci_ir_requerido"));
            saveErrors(request, errors);
            error = true;
        }
        String imagePath = request.getParameter("imagePath");

        if (error) {
            return mapping.findForward(FAILURE);
        }

        Map parametros = new HashMap();
        parametros.put("ci", cedula);
        parametros.put("r_puesto_trabajador", r_puesto_trabajador);
        parametros.put("examenes_medicos", examenes_medicos);
        parametros.put("imagePath", imagePath);

        InformeRiesgos_DAO inf = new InformeRiesgos_DAO();
        informePDF = inf.generarInforme(parametros);

        response.setContentType("application/pdf");
        response.setHeader("Cache-Control", "cache");
        response.setHeader("Pragma", "cache");
        response.setHeader("Content-Disposition", "attachment; filename=informeRiesgos.pdf");
        response.setContentLength(informePDF.length);
        ServletOutputStream outputStream = response.getOutputStream();

        outputStream.write(informePDF);
        outputStream.flush();
        outputStream.close();
        /*

        //parametros.put("SUBREPORT_DIR", "");
        Map parametro = new HashMap();
        parametro.put("ci", cedula);

        InformeRiesgos_DAO inf = new InformeRiesgos_DAO();
        InformeRiesgos2_DAO inf2 = new InformeRiesgos2_DAO();

        informePDF = inf.generarInforme(parametros);
        informePDF2 = inf2.generarInforme(parametro);

        if (informePDF == null) {
            formBean.setError("Error obteniendo el informe de riesgos. Intente Nuevamente");
            return mapping.findForward(FAILURE);
        }

        PdfReader reader1 = new PdfReader(informePDF);
        PdfReader reader2 = new PdfReader(informePDF2);
        String filePath = getServlet().getServletContext().getRealPath("/") + "Modulo3/archivosNT/informeRiesgos.pdf";
        PdfCopyFields copy = new PdfCopyFields(new FileOutputStream(filePath));
        copy.addDocument(reader1);
        copy.addDocument(reader2);
        copy.close();

        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename=Informe_de_Riesgos.pdf");

        InputStream archivo = new FileInputStream(filePath);
        ServletOutputStream outs = response.getOutputStream();

        int bit = 256;
        int i = 0;

        while ((bit) >= 0) {
            bit = archivo.read();
            outs.write(bit);
        }

        outs.flush();
        outs.close();
        archivo.close();


        /*response.setContentType("application/pdf");
        response.setHeader("Cache-Control", "cache");
        response.setHeader("Pragma", "cache");
        response.setHeader("Content-Disposition", "attachment; filename=Informe_de_Riesgos.pdf");

        response.setContentLength(informePDF.length);

        ServletOutputStream outputStream = response.getOutputStream();

        outputStream.write(informePDF);
        outputStream.flush();
        outputStream.close();*/

        
        return mapping.findForward(SUCCESS);
    }
}
